package com.yyge.controller;

import cn.hutool.crypto.digest.BCrypt;
import com.yyge.context.JwtContext;
import com.yyge.context.RedisContext;
import com.yyge.dto.LoginDto;
import com.yyge.dto.R;
import com.yyge.dto.ResultCode;
import com.yyge.entity.AdminUser;
import com.yyge.service.AdminUserService;
import com.yyge.util.TokenUtil;
import com.yyge.vo.LoginVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

@RestController
public class LoginController {
    @Autowired
    private RedisContext redisContext;

    @Autowired
    private JwtContext jwtContext;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private AdminUserService service;

    @Autowired
    private TokenUtil tokenUtil;
    @PostMapping("login")
    public R login(@Valid @RequestBody LoginDto loginDto){

        System.out.println(loginDto);
        //根据UUID获取验证码
        String uuid=loginDto.getUuid();

        //获取redis中验证码的key
        String key=redisContext.getCaptchaKey(uuid);


        //到redis中获取验证码
        Object value=redisTemplate.opsForValue().get(key);
        if(value == null){
            //验证码失效
            return R.error(ResultCode.SYSTEM_CODE_INVALID);
        }

         //消费验证码(从redis中删除)
        redisTemplate.delete(key);

        //获取验证码
        String code=value.toString();

        if (!code.equalsIgnoreCase(loginDto.getCode())){
            //验证码失效
            return R.error(ResultCode.SYSTEM_CODE_ERROR);
        }
        AdminUser adminUser=service.findByName(loginDto.getLoginName());
        if(adminUser == null){
            //用户不存在
            return R.error(ResultCode.ACCOUNT_NOT_EXISTS);
        }

        //验证密码
        if(!BCrypt.checkpw(loginDto.getLoginPwd(),adminUser.getLoginPassword())){
            //密码错误
            return R.error(ResultCode.ACCOUNT_INVALID_PWD);

        }

        //状态验证
        if(adminUser.getLocked() != AdminUser.STATUS_OK){
            //状态错误
            return R.error(ResultCode.ACCOUNT_INVALID);
        }
        System.out.println("===============404");
        String token=tokenUtil.createToken(adminUser);

        return R.ok(token);
    }

   @PostMapping("logout")
   public R logout(@RequestHeader("Authorization") String auth){
        tokenUtil.removeRedisToken(auth);
        return R.ok();
   }


    @GetMapping("/user/info")
    //@RequestHeader 获取请求头中指定key的值
    public R getInfo(@RequestHeader("Authorization") String auth){
        LoginVO vo = tokenUtil.getLoginVO(auth);
        if(vo == null){
            return R.error(ResultCode.SYSTEM_TOKEN_INVALID);
        }
        return R.ok(vo);
    }


}
